<?php

declare(strict_types=1);
/**
 * 创建人 : Forpastime
 * 创建时间: 2023/4/10 14:45
 * 个人主页 : http://forpastime.com
 */
namespace App\Service;

use App\Model\Admin;
use App\Model\Node;
use App\Model\Role;
use App\Utils\Result;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;

class AdminService implements AdminServiceInterface
{
    /**
     * @Inject()
     * @var Admin
     */
    protected $admin;

    /**
     * @Inject()
     * @var Role
     */
    protected $role;

    /**
     * @Inject()
     * @var Node
     */
    protected $node;

    /**
     * @var Redis
     * @Inject()
     */
    protected $redis;

    /**
     * {@inheritDoc}
     */
    public function login($data)
    {
        // TODO: Implement login() method.
       $info = $this->admin->where('user_name',$data['username'])->where('password',md5($data['password'].env('AUTH_SOLT')))->first();
        if(!$info){
            return Result::data_error('用户名或密码错误');
        }else{
            $info = $info->toArray();
        }
       if($info['role_id']==1){
            //超级管理员角色 不需要查库
            $menuData = $this->node->getMenu('*');
        }else if($info['status']==0){
            //用户禁用
            return Result::return([],-1,'该账号已被禁用');
        }else{
            $nodes = $this->role->getOneRole($info['role_id']);
            $menuData = $this->node->getMenu($nodes['rule']);
        }
       //这里将每个角色的node存入redis
        $redis = ApplicationContext::getContainer()->get(Redis::class);
       $redis->set('HyperCMF:role_menu_data:'.$info['role_id'],json_encode($menuData->toArray()));
       $menu = for_prepare_menu($menuData);

        $this->admin->where('id',$info['id'])->increment('login_times');

        $res['avatar'] = $info['avatar'];
        $res['id'] = $info['id'];
        $res['role_id'] = $info['role_id'];
        $res['menu'] = $menu;
        return Result::data_success($res);

    }

    /**
     * {@inheritDoc}
     */
    public function editInfo($data)
    {
        return $this->admin->where('id',$data['id'])->update($data);
    }

    /**
     * {@inheritDoc}
     */
    public function editPwd($data)
    {
        // TODO: Implement editPwd() method.
        if(!isset($data['id']) || empty($data['id'])){
            return false;
        }
        return $this->admin->where('id',$data['id'])->update(['password'=>md5($data['password'].env('AUTH_SOLT'))]);
    }

    /**
     * {@inheritDoc}
     */
    public function changeMobile($data)
    {
        // TODO: Implement changeMobile() method.
    }

    /**
     * 添加角色角色
     * @param $data
     * @return mixed
     */
    public function addRole($data)
    {
        if(empty($data)){
            return false;
        }
        return $this->role->insertRole($data);
    }


    /**
     * 修改角色
     * @param $id
     * @param $data
     * @return mixed
     */
    public function editRole($id,$data)
    {
        if(empty($data) || empty($id)){
            return false;
        }
        $res = $this->role->editRole($id,$data);
        return $res;
    }

    /**
     * {@inheritDoc}
     */
    public function delRole($id)
    {
        // TODO: Implement delRole() method.
    }

    /**
     * {@inheritDoc}
     */
    public function roles()
    {
        // TODO: Implement roles() method.
    }

    /**
     * {@inheritDoc}
     */
    public function authorizations()
    {
        // TODO: Implement authorizations() method.
    }

    /**
     * {@inheritDoc}
     */
    public function eidtAuth()
    {
        // TODO: Implement eidtAuth() method.
    }

    /**
     * {@inheritDoc}
     */
    public function addAccount($data)
    {
        if(empty($data)){
            return false;
        }
        if(isset($data['password']) && !empty($data['password'])){
            $data['password'] = md5($data['password'].env('AUTH_SOLT'));
        }
        return $this->admin->add($data);

    }

    /**
     * {@inheritDoc}
     */
    public function editAccount($id,$data)
    {
        if(empty($data) || empty($id)){
            return false;
        }
        if(isset($data['password']) && !empty($data['password'])){
            $data['password'] = md5($data['password'].env('AUTH_SOLT'));
        }
        //更新管理与角色缓存
        $this->redis->set('HyperfCMF:admin_role:'.$data['user_name'],$data['role_id']);

        $res = $this->admin->edit($id,$data);
        return $res;
    }

    /**
     * 获取管理员列表
     * @param $where
     * @param string $field
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Query\Builder
     */
    public function getUsers($where,$field='*',$limit=10)
    {
        $list = $this->admin->getUsers($where,$field,$limit);
        return $list;
    }

    /**
     * 获取单个用户
     * @param $where
     * @param string $field
     * @return array
     */
    public function getUser($where,$field='*')
    {
        $admin = $this->admin->getOne($where,$field);
        return $admin;
    }

    /**
     * 获取角色列表
     * @param $where
     * @param string $field
     * @param int $limit
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Query\Builder
     */
    public function getRoles($where,$field='*',$limit=10)
    {
        $list = $this->role->getRoleByWhere($where,$field,$limit);
        return $list;
    }

    public function getPower($id){
        $nodes = $this->role->getOneRole($id);
        $menu = $this->node->getPowerList(explode(',',$nodes['rule']));
        return $menu;
    }

    public function setPower($data)
    {
        $menuPower = $actionPower = [];
        foreach ($data['nodes'] as $val){
            if($val['type']==1){
                $menuPower[] = $val['control_name'].'/'.$val['action_name'];
            }else if($val['type']==2){
                $actionPower[] = $val['control_name'].'/'.$val['action_name'];
            }
        }
        $redis = ApplicationContext::getContainer()->get(Redis::class);
        $redis->set("HyperCMF:menu_power_routes:".$data['id'],implode(',',$menuPower));
        $redis->set("HyperCMF:action_power_routes:".$data['id'],implode(',',$actionPower));
    }
}
